<template>
	<div class='gobang-canvas'>
		<canvas
			id="gobang-canvas"
      :width="canvasWidth"
      :height="canvasHeight"
			color-space="srgb"
			style="background-color: #EECE9F;"
		>
      Your browser does not support the HTML5 canvas tag.
		</canvas>
	</div>
</template>

<script setup name='GobangCanvas'>
import { ref, onMounted, nextTick } from 'vue'

const ctx = ref()
const canvasWidth = ref(600) // 画布宽度
const canvasHeight = ref(600) // 画布高度
const latticeCountX = ref(20) // 格子数
const latticeWidth = ref(40) // 格子宽度
const draugftInfo = ref([]) // 棋盘信息 0 空 1 白棋 2 黑棋

canvasWidth.value = latticeWidth.value * latticeCountX.value
canvasHeight.value = latticeWidth.value * latticeCountX.value
draugftInfo.value = new Array(latticeCountX.value+1).fill(0).map(() => new Array(latticeCountX.value+1).fill(0))
console.log('draugftInfo.value---', draugftInfo.value)

// 挂载后
onMounted(() => {
	init()
})
const init = async () => {
	await nextTick()
	let canvas = document.getElementById('gobang-canvas')
	try {
		ctx.value = canvas.getContext('2d')
	} catch (error) {
		console.log('canvas,ctx,getContext', error)
	}
	// drawDraughtBoard() // 绘制棋盘
	// drawWinner() // 绘制获胜者
	// drawDraught(12, 8, '#fff') // 绘制棋子-白
	// drawDraught(12, 9, '#000') // 绘制棋子-黑
}

/** 绘制棋盘 */
const drawDraughtBoard = () => {
	ctx.value.clearRect(0, 0, canvasWidth.value, canvasHeight.value)
	// 绘制棋盘
	ctx.value.save();
	ctx.value.translate(0.5, 0.5);
	// ctx.value.strokeStyle = '#fff'
	// ctx.value.lineWidth = 2
	// ctx.value.strokeRect(0, 0, canvasWidth.value, canvasHeight.value) // 边框
	// 绘制棋盘格
	ctx.value.strokeStyle = '#666'
	ctx.value.lineWidth = 1
	for (let i = 0; i < latticeCountX.value; i++) {
		ctx.value.beginPath()
		ctx.value.moveTo(i * latticeWidth.value, 0)
		ctx.value.lineTo(i * latticeWidth.value, canvasHeight.value)
		ctx.value.stroke()
		ctx.value.beginPath()
		ctx.value.moveTo(0, i * latticeWidth.value)
		ctx.value.lineTo(canvasWidth.value, i * latticeWidth.value)
		ctx.value.stroke()
	}
	ctx.value.restore();
}

/** 绘制棋子 */
const drawDraught = (x, y, color) => {
	ctx.value.save();
	ctx.value.translate(0.5, 0.5);
	ctx.value.fillStyle = color
	ctx.value.beginPath()
	ctx.value.arc(x * latticeWidth.value, y * latticeWidth.value, latticeWidth.value / 2, 0, Math.PI * 2)
	ctx.value.fill()
	ctx.value.restore();
}

/** 绘制获胜者 */
const drawWinner = () => {

}

</script>
<style lang='scss' scoped>
#gobang-canvas {
 cursor: pointer;
 border: 2px solid #000;
}
</style>
